package com.mapaower.admin.service;

import com.mapaower.admin.entity.Permission;
import com.mapaower.admin.repository.PermissionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class PermissionService {

    @Autowired
    private PermissionRepository permissionRepository;

    public Permission getPermissionById(Long id) {
        return permissionRepository.findById(id).orElse(null);
    }

    public Permission getPermissionByName(String name) {
        return permissionRepository.findByName(name).orElse(null);
    }

    public Permission getPermissionByKey(String permissionKey) {
        return permissionRepository.findByPermissionKey(permissionKey).orElse(null);
    }

    public List<Permission> getAllPermissions() {
        return permissionRepository.findAll();
    }

    @Transactional
    public Permission createPermission(Permission permission) {
        if (permissionRepository.existsByName(permission.getName())) {
            throw new RuntimeException("权限名称已存在");
        }
        if (permissionRepository.existsByPermissionKey(permission.getPermissionKey())) {
            throw new RuntimeException("权限标识已存在");
        }

        return permissionRepository.save(permission);
    }

    @Transactional
    public Permission updatePermission(Long id, Permission permission) {
        Permission existingPermission = getPermissionById(id);
        if (existingPermission == null) {
            throw new RuntimeException("权限不存在");
        }

        // 更新权限名称
        if (permission.getName() != null && !permission.getName().equals(existingPermission.getName())) {
            if (permissionRepository.existsByName(permission.getName())) {
                throw new RuntimeException("权限名称已存在");
            }
            existingPermission.setName(permission.getName());
        }

        // 更新权限描述
        if (permission.getDescription() != null) {
            existingPermission.setDescription(permission.getDescription());
        }

        // 更新权限标识
        if (permission.getPermissionKey() != null && !permission.getPermissionKey().equals(existingPermission.getPermissionKey())) {
            if (permissionRepository.existsByPermissionKey(permission.getPermissionKey())) {
                throw new RuntimeException("权限标识已存在");
            }
            existingPermission.setPermissionKey(permission.getPermissionKey());
        }

        return permissionRepository.save(existingPermission);
    }

    @Transactional
    public boolean deletePermission(Long id) {
        if (!permissionRepository.existsById(id)) {
            return false;
        }

        permissionRepository.deleteById(id);
        return true;
    }
}